package com.example.base.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;

import android.annotation.SuppressLint;
import android.os.Bundle;


import android.view.MenuItem;

import com.example.base.R;
import com.example.base.adapter.ViewPagerAdapter;
import com.example.base.fragment.HomeFragment;
import com.example.base.fragment.MineFragment;
import com.example.base.fragment.QuestionFragment;
import com.example.base.fragment.TryFragment;
import com.google.android.material.bottomnavigation.BottomNavigationView;


public class MainActivity extends AppCompatActivity {
  private ViewPager viewPager;
  private MenuItem menuItem;
  private BottomNavigationView bottomNavigationView;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    initView();
    initListener();

  }

  private void initListener() {
    NavigationSelectedListener();
    ViewPagerChangeListener();

  }

  private void ViewPagerChangeListener() {
    viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
      @Override
      public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

      }

      @Override
      public void onPageSelected(int position) {
        if (menuItem != null) {
          menuItem.setChecked(false);
        } else {
          bottomNavigationView.getMenu().getItem(0).setChecked(false);
        }
        menuItem = bottomNavigationView.getMenu().getItem(position);
        menuItem.setChecked(true);
      }

      @Override
      public void onPageScrollStateChanged(int state) {
      }
    });
    setupViewPager(viewPager);
    viewPager.setOffscreenPageLimit(4);
  }

  @SuppressLint("NonConstantResourceId")
  private void NavigationSelectedListener() {
    bottomNavigationView.setOnNavigationItemSelectedListener(
        item -> {
          switch (item.getItemId()) {
            case R.id.home:
              viewPager.setCurrentItem(0);
              break;
            case R.id.question:
              viewPager.setCurrentItem(1);
              break;
            case R.id.system:
              viewPager.setCurrentItem(2);
              break;
            case R.id.mine:
              viewPager.setCurrentItem(3);
              break;
            default:
              break;
          }
          return false;
        });
  }

  private void initView() {
    viewPager = findViewById(R.id.viewPager);
    bottomNavigationView = findViewById(R.id.bnv1);
  }

  private void setupViewPager(ViewPager viewPager) {
    ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
    adapter.addFragment(new HomeFragment());
    adapter.addFragment(new QuestionFragment());
    adapter.addFragment(new TryFragment());
    adapter.addFragment(new MineFragment());
    viewPager.setAdapter(adapter);
  }

}